from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.core.exceptions import ValidationError

from .models import Order, Cart, OrderLog
from .serializers import (
    OrderListSerializer, OrderDetailSerializer, OrderCreateSerializer,
    CartSerializer, CartCreateSerializer, CartUpdateSerializer,
    OrderLogSerializer, PaymentSerializer
)
from .services import OrderService, CartService, PaymentService, OrderLogService, OrderStatisticsService
from common.utils.response import APIResponse


class OrderViewSet(viewsets.ModelViewSet):
    """订单视图集"""
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Order.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderListSerializer
        elif self.action == 'create':
            return OrderCreateSerializer
        return OrderDetailSerializer

    def list(self, request, *args, **kwargs):
        """获取订单列表"""
        try:
            status_filter = request.query_params.get('status')
            orders = OrderService.get_user_orders(request.user.id, status_filter)
            
            # 分页
            page = self.paginate_queryset(orders)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            
            serializer = self.get_serializer(orders, many=True)
            return APIResponse.success(data=serializer.data, message="获取订单列表成功")
        except Exception as e:
            return APIResponse.error(message=f"获取订单列表失败: {str(e)}")

    def retrieve(self, request, *args, **kwargs):
        """获取订单详情"""
        try:
            order = OrderService.get_order_detail(kwargs['pk'], request.user.id)
            serializer = self.get_serializer(order)
            return APIResponse.success(data=serializer.data, message="获取订单详情成功")
        except ValidationError as e:
            return APIResponse.not_found(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"获取订单详情失败: {str(e)}")

    def create(self, request, *args, **kwargs):
        """创建订单"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                order = OrderService.create_order(
                    user_id=request.user.id,
                    cart_ids=serializer.validated_data['cart_ids'],
                    address_id=serializer.validated_data['address_id'],
                    remark=serializer.validated_data.get('remark'),
                    delivery_time=serializer.validated_data.get('delivery_time')
                )
                return APIResponse.success(
                    data=OrderDetailSerializer(order).data,
                    message="创建订单成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"创建订单失败: {str(e)}")

    @action(detail=True, methods=['post'])
    def cancel(self, request, pk=None):
        """取消订单"""
        try:
            reason = request.data.get('reason', '用户取消')
            order = OrderService.cancel_order(pk, request.user.id, reason)
            return APIResponse.success(
                data=OrderDetailSerializer(order).data,
                message="取消订单成功"
            )
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"取消订单失败: {str(e)}")

    @action(detail=True, methods=['post'])
    def confirm(self, request, pk=None):
        """确认收货"""
        try:
            order = OrderService.confirm_receipt(pk, request.user.id)
            return APIResponse.success(
                data=OrderDetailSerializer(order).data,
                message="确认收货成功"
            )
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"确认收货失败: {str(e)}")

    @action(detail=True, methods=['get'])
    def logs(self, request, pk=None):
        """获取订单日志"""
        try:
            # 验证订单是否属于当前用户
            OrderService.get_order_detail(pk, request.user.id)
            logs = OrderLogService.get_order_logs(pk)
            serializer = OrderLogSerializer(logs, many=True)
            return APIResponse.success(data=serializer.data, message="获取订单日志成功")
        except ValidationError as e:
            return APIResponse.not_found(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"获取订单日志失败: {str(e)}")

    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def statistics(self, request):
        """获取订单统计"""
        try:
            # 直接使用中间件设置的用户信息
            if not request.user or not hasattr(request.user, 'id'):
                return APIResponse.error(message="用户未登录", code=401)
            
            stats = OrderStatisticsService.get_user_order_stats(request.user.id)
            return APIResponse.success(data=stats, message="获取订单统计成功")
        except Exception as e:
            return APIResponse.error(message=f"获取订单统计失败: {str(e)}")

    @action(detail=False, methods=['post'])
    def payment(self, request):
        """创建支付"""
        try:
            serializer = PaymentSerializer(data=request.data)
            if serializer.is_valid():
                order_id = serializer.validated_data['order_id']
                payment_method = serializer.validated_data['payment_method']
                
                # 验证订单是否属于当前用户
                OrderService.get_order_detail(order_id, request.user.id)
                
                payment_params = PaymentService.create_payment(order_id, payment_method)
                return APIResponse.success(
                    data=payment_params,
                    message="创建支付成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"创建支付失败: {str(e)}")


class CartViewSet(viewsets.ModelViewSet):
    """购物车视图集"""
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Cart.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'create':
            return CartCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return CartUpdateSerializer
        return CartSerializer

    def list(self, request, *args, **kwargs):
        """获取购物车列表"""
        try:
            cart_items = CartService.get_user_cart(request.user.id)
            serializer = self.get_serializer(cart_items, many=True)
            
            # 获取购物车总计
            cart_total = CartService.get_cart_total(request.user.id)
            
            return APIResponse.success(
                data={
                    'items': serializer.data,
                    'total': cart_total
                },
                message="获取购物车成功"
            )
        except Exception as e:
            return APIResponse.error(message=f"获取购物车失败: {str(e)}")

    def create(self, request, *args, **kwargs):
        """添加到购物车"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                cart_item = CartService.add_to_cart(
                    user_id=request.user.id,
                    flower_id=serializer.validated_data['flower'].id,
                    flower_spec_id=serializer.validated_data.get('flower_spec').id if serializer.validated_data.get('flower_spec') else None,
                    quantity=serializer.validated_data['quantity']
                )
                return APIResponse.success(
                    data=CartSerializer(cart_item).data,
                    message="添加到购物车成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"添加到购物车失败: {str(e)}")

    def update(self, request, *args, **kwargs):
        """更新购物车商品数量"""
        try:
            serializer = self.get_serializer(data=request.data, partial=True)
            if serializer.is_valid():
                cart_item = CartService.update_cart_quantity(
                    cart_id=kwargs['pk'],
                    user_id=request.user.id,
                    quantity=serializer.validated_data['quantity']
                )
                return APIResponse.success(
                    data=CartSerializer(cart_item).data,
                    message="更新购物车成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"更新购物车失败: {str(e)}")

    def destroy(self, request, *args, **kwargs):
        """从购物车移除商品"""
        try:
            CartService.remove_from_cart(kwargs['pk'], request.user.id)
            return APIResponse.success(message="移除商品成功")
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"移除商品失败: {str(e)}")

    @action(detail=False, methods=['delete'])
    def clear(self, request):
        """清空购物车"""
        try:
            CartService.clear_cart(request.user.id)
            return APIResponse.success(message="清空购物车成功")
        except Exception as e:
            return APIResponse.error(message=f"清空购物车失败: {str(e)}")

    @action(detail=False, methods=['get'], permission_classes=[AllowAny])
    def total(self, request):
        """获取购物车总计"""
        try:
            # 直接使用中间件设置的用户信息
            if not request.user or not hasattr(request.user, 'id'):
                return APIResponse.error(message="用户未登录", code=401)
            
            cart_total = CartService.get_cart_total(request.user.id)
            return APIResponse.success(data=cart_total, message="获取购物车总计成功")
        except Exception as e:
            return APIResponse.error(message=f"获取购物车总计失败: {str(e)}")
